package com.phone.store.service.impl;

import com.phone.store.entity.BuyerAddress;
import com.phone.store.form.AddressForm;
import com.phone.store.repository.BuyerAddressRepository;
import com.phone.store.service.AddressService;
import com.phone.store.vo.AddressVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fangyu
 * @version v1.0.0
 * @date 2020/7/31 9:51 下午
 */
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private BuyerAddressRepository buyerAddressRepository;

    @Override
    public List<AddressVO> findAll() {
        List<AddressVO> list = buyerAddressRepository.findAll().stream()
                .map(buyerAddress -> new AddressVO(
                        buyerAddress.getAddressId(),
                        buyerAddress.getAreaCode(),
                        buyerAddress.getBuyerName(),
                        buyerAddress.getBuyerPhone(),
                        buyerAddress.getBuyerAddress()
                )).collect(Collectors.toList());

        return list;
    }

    @Override
    public void saveOrUpdateAddress(AddressForm addressForm) {
        BuyerAddress buyerAddress;
        // 如果form传进来的地址为空，则新建，不为空则去数据库查询
        if (addressForm.getId() == null) {
            buyerAddress = new BuyerAddress();
        } else {
            buyerAddress = buyerAddressRepository.findById(addressForm.getId()).get();
        }

        buyerAddress.setBuyerName(addressForm.getName());
        buyerAddress.setBuyerPhone(addressForm.getTel());

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(addressForm.getProvince())
                .append(addressForm.getCity())
                .append(addressForm.getCounty())
                .append(addressForm.getAddressDetail());
        buyerAddress.setBuyerAddress(stringBuffer.toString());
        buyerAddress.setAreaCode(addressForm.getAreaCode());

        buyerAddressRepository.save(buyerAddress);
    }
}
